package com.inspectortime.webapp.admin;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.inspectortime.domain.User;
import com.inspectortime.repository.Repository;
import com.inspectortime.util.DesLocalMachineEncrypter;
import com.inspectortime.webapp.util.HttpSessionUtils;

public class BecomeSomeoneServiceController implements Controller {

	private String successView;
	
	public void setSuccessView(String successView) {
		this.successView = successView;
	}

	public void setRepository(Repository repository) {
		this.repository = repository;
	}

	private Repository repository;

	private static Log log = LogFactory.getLog(BecomeSomeoneServiceController.class);

	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		if (!request.getMethod().equalsIgnoreCase("POST")) {
			throw new RuntimeException("Only POST requests supported");
		}
		String encryptedEmail = request.getParameter("code");
		DesLocalMachineEncrypter encrypter = new DesLocalMachineEncrypter();
		String email = encrypter.decrypt(encryptedEmail);
		
		User user = repository.findUserByEmail(email);
		HttpSessionUtils.storeLoggedInUser(request, user);
		log.info("Emulating user: " + user.getEmail());
		
		return new ModelAndView(successView);
	}

}
